import {MdEditor} from 'md-editor-rt';
import {useEffect, useState} from "react";
import {useParams} from "react-router-dom";
import {editArticleUrl, getArticleInfoByIdUrl} from "@/api/blog/article.ts";
import {globalMessageApi} from "@/components/OpComponent/Message";
import {uploadProjectUrl} from "@/api/file.ts";
import {getUploadUrl, UploadIssueEnum, UploadProjectEnum} from "@/utils/upload.ts";
import {PageWrapperBox, WholePageContent, WholePageHeader} from "@/layout/Page";
import 'md-editor-rt/lib/style.css';

export default function EditArticle() {
    const [text, setText] = useState('hello md-editor-rt!');
    const {artId}: any = useParams()
    useEffect(() => {
        getArticleInfoByIdUrl({artId: artId}).then((res: any) => {
            setText(res.data.artContent || "")
        })
    }, [])

    function handleSave() {
        editArticleUrl({
            artId: artId,
            artContent: text
        }).then((res) => {
            globalMessageApi.success(res.msg)
        })
    }

    const handleUpload = async (files: any, callback: any) => {
        const file = files[0]
        const formData = new FormData();
        formData.append('files', file, file.name)
        const res: any = await uploadProjectUrl(getUploadUrl(UploadProjectEnum.ARTICLE_PRO_03, UploadIssueEnum.ARTICLE_CONTENT, artId), formData)
        callback(res.data.map((item: any) => item.url));
    }

    return <PageWrapperBox>
        <WholePageHeader title={"编辑文章"} to={"/blog/articles"}/>
        <WholePageContent>
            <MdEditor modelValue={text}
                      onChange={setText}
                      onSave={handleSave}
                      onUploadImg={handleUpload}
                      style={{height: 'calc(100vh - 280px)'}}
            />
        </WholePageContent>
    </PageWrapperBox>
}
